<template>
    <div class="content-body">

        <el-card class="content">
            <el-button @click="dialogFormVisibleChange" type="primary" icon="el-icon-circle-plus" circle size="mini">
            </el-button>
            <!-- //表格 -->
            <el-table class="content-center" ref="multipleTable" :data="docs" tooltip-effect="dark" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="用户名" width="width">
                    <template slot-scope="scope">{{ scope.row.userName }}</template>
                </el-table-column>
                <el-table-column prop="group.name" label="用户类型" width="width">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="width">
                </el-table-column>
                <el-table-column prop="phoneNum" label="手机号" width="width">
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="width">
                </el-table-column>
                <el-table-column prop="auth" label="是否有效" width="width">
                    <svg v-show="!ruleForm.auth" t="1654871945988" class="icon" viewBox="0 0 1024 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="2571" width="16" height="16">
                        <path
                            d="M512 64C265 64 64 265 64 512s201 448 448 448 448-201 448-448S759 64 512 64z m-67 627.4l-0.2-0.2-0.2 0.2-179.2-179.2 45.2-45.2 134.2 134.1 268.6-268.5 45.2 45.2L445 691.4z"
                            fill="#1afa29" p-id="2572"></path>
                    </svg>
                    <svg v-show="ruleForm.auth" t="1654949880820" class="icon" viewBox="0 0 1024 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="2230" width="16" height="16">
                        <path
                            d="M512 32C251.4285715625 32 32 251.4285715625 32 512s219.4285715625 480 480 480 480-219.4285715625 480-480-219.4285715625-480-480-480z m205.7142853125 617.142856875c20.5714284375 20.5714284375 20.5714284375 48 0 61.714286249999994-20.5714284375 20.5714284375-48 20.5714284375-61.714285312499996 0l-137.142856875-137.1428578125L374.857143125 717.7142853125c-20.5714284375 20.5714284375-48 20.5714284375-68.5714284375 0s-20.5714284375-54.857143125 0-68.5714284375l144-144-137.1428578125-137.142856875c-20.5714284375-13.714285312500001-20.5714284375-41.142856875 0-61.714285312499996 20.5714284375-20.5714284375 48-20.5714284375 61.714286249999994 0l137.142856875 137.142856875 144-144c20.5714284375-20.5714284375 48-20.5714284375 68.5714284375 0 20.5714284375 20.5714284375 20.5714284375 48 0 68.5714284375L580.5714284375 512l137.142856875 137.142856875z"
                            fill="#d81e06" p-id="2231"></path>
                    </svg>
                </el-table-column>
                <el-table-column prop="name" label="操作" width="width">
                    <template slot-scope="{row,$index}">
                        <el-button @click="lookDiary(row)" class="clear_danger" type="warning"
                            icon="el-icon-document-copy" circle size="mini"></el-button>
                        <el-button @click="deleteRow(row)" class="delete_danger" type="danger" icon="el-icon-delete"
                            circle size="mini">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- //分页器 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="pageInfo.current" :page-sizes="[10, 30, 50]" :page-size="pageInfo.pageSize"
                layout="total,sizes, prev, pager, next" :total="pageInfo.totalItems"></el-pagination>
        </el-card>
        <!-- //表单 1-->
        <!-- Form :model="form"-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" :data="docs">
                <el-form-item label="用户名 " type="text" prop="userName">
                    <el-input v-model="ruleForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="姓名 " type="text" prop="name">
                    <el-input v-model="ruleForm.name" autocomplete="on"></el-input>
                </el-form-item>
                <!-- //照片墙 -->
                <el-form-item label="头像 ">
                    <el-upload class="avatar-uploader" action="http://127.0.0.1:8080/api/upload/files"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="url" :src="url" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="url" alt="">
                    </el-dialog>
                </el-form-item>
                <el-form-item label="密码 " type="text" prop="password">
                    <el-input v-model="ruleForm.password" type="password" placeholder="不修改密码请留空" autocomplete="on">
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码 " type="text" prop="confirmPwd">
                    <el-input v-model="ruleForm.confirmPwd" type="password" placeholder="不修改密码请留空"></el-input>
                </el-form-item>
                <el-form-item label="用户类型 " prop="userType">
                    <el-select v-model="ruleForm.group.name" placeholder="请选择">
                        <el-option v-for="item in docsType" :key="item._id" :label="item.label" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="国家码 " prop="countryCode">
                    <el-select v-model="ruleForm.countryCode" placeholder="请选择">
                        <el-option v-for="item in code" :key="item.id" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>

                </el-form-item>
                <el-form-item label="手机号 " prop="phoneNum">
                    <el-input v-model="ruleForm.phoneNum"></el-input>
                </el-form-item>
                <el-form-item label="邮箱 " prop="email">
                    <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>

                <el-form-item label="是否有效">
                    <el-switch v-model="ruleForm.enable"></el-switch>
                </el-form-item>

                <el-form-item label="备注" prop="comments">
                    <el-input type="textarea" v-model="ruleForm.comments"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button v-if="type == 1" @click="submitForm('ruleForm')" type="primary">保存</el-button>
                    <el-button v-else @click="submitForm('ruleForm')" type="primary">更新</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
import { reqAdminGroup, reqAdminUser, reqUpdateOne, reqDeleteUser, reqAddOne, reqGetOne, reqGetPage } from '@/api/adminUser'


export default {
    name: '',
    data() {
        const validateConfirmPwd = (rule, value, callback) => {
            if (value === "") {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            //分页信息
            pageInfo: {
                current: 1,
                pageSize: 10,
                total: 0,
                // totalPage: 0
            },
            //添加管理员控件
            dialogFormVisible: false,
            code: [
                {
                    value: '中国+86',
                    label: '中国+86'
                }
            ],
            docs: [],
            docsType: [],
            show: false,
            multipleSelection: [],
            //头像
            dialogVisible: false,
            ruleForm: {
                logo: ' ',
                userName: '',
                name: '',
                password: '',
                confirmPwd: '',
                user: '',
                countryCode: '',
                phoneNum: '',
                email: '',
                comments: '',
                auth: false,
                date: '',
                enable: false,
                group: {
                    name: '',
                    power: [],
                    _id: ''
                },
                state: '',
                __v: '',
                _id: '',


            },
            rules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' },
                    { pattern: /^[\u3a00-\ufa99a-zA-Z]{5,12}$/, message: '只能输入5-12位的中文或者英文字母', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' },
                    { pattern: /^[\u4e00-\u9fa5]+$/, message: '只能输入2-6位的中文', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                    { pattern: /^[A-Za-z0-9_]{6,12}$/, message: '只能包含字母、数字和下划线!', trigger: 'blur' }
                    // { validator: validatePass, trigger:'blur'}
                ],
                confirmPwd: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '两次输入的不一致', trigger: 'blur' },
                    { validator: validateConfirmPwd, trigger: 'blur' }

                ],
                userType: [
                    // { required: true, message: '请至少选择一个活动性质', trigger: 'change' }
                ],
                user: [
                    { required: true }

                ],
                countryCode: [
                    { required: true, message: '请选择国家码', trigger: 'change' }
                ],
                phoneNum: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
                        , message: '手机号不合法', trigger: 'blur'
                    }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                        , message: '请输入正确的邮箱格式例如QQ邮箱123456789@qq.com或者 abc123@163.com', trigger: 'blur'
                    }
                ],
                comments: [
                    { required: true, message: '请输入备注', trigger: 'blur' }
                ],
            },
            formLabelWidth: '120px',
            title: '',
            type: '',
            url: ''

        }

    },
    methods: {
        //图片上传成功
        handleAvatarSuccess(res, file, fileList) {
            // console.log(res)
            // console.log(file)
            // console.log(fileList)
            this.url = URL.createObjectURL(file.raw);
            this.ruleForm.logo = URL.createObjectURL(file.raw);
            console.log(this.url);

        },
        //保存用户名和密码
        setUserName() {
            window.localStorage.setItem(this.ruleForm.name, this.ruleForm.password)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        deleteRow(row) {
            this.$confirm('此操作将永久删除用户，是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                reqDeleteUser({ ids: row._id }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    //挂载用户管理
                    this.getrAdminUser()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //显示修改、添加对话框
        dialogFormVisibleChange() {
            this.title = '新增用户信息'
            this.type = 1
            this.dialogFormVisible = true
            this.ruleForm = {
                group: {
                    name: '',
                    power: [],
                    _id: ''
                },
            }

        },
        //添加用户
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.setUserName()
                    if (this.ruleForm.group.name == '测试用户组') {
                        this.ruleForm.group._id = 'EydZWWiR'
                    } else {
                        this.ruleForm.group._id = 'E1XjEmqA'
                    }
                    //    this.ruleForm.group._id = id
                    //  console.log(id,'888')
                    if (this.type == 1) {
                        const { _id } = this.ruleForm.group
                        let result = await reqAddOne({ ...this.ruleForm })
                        if (result.status == 200) {
                            this.$message({ type: 'success', message: '添加成功' })
                            this.dialogFormVisible = false
                            //挂载用户管理
                            this.getrAdminUser()
                        } else {
                            this.$message({ type: 'warning', message: '添加失败' })
                        }
                    } else {
                        let reuslt = await reqUpdateOne({ ...this.ruleForm })
                        if (reuslt.status == 200) {
                            this.$message({ type: 'success', message: '更新成功' })
                            this.dialogFormVisible = false
                            //挂载用户管理
                            this.getrAdminUser()
                        } else {
                            this.$message({ type: 'warning', message: '更新失败' })
                        }
                        this.ruleForm = {
                            group: {
                                name: '',
                                power: [],
                                _id: ''
                            },
                        }
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });

        },
        //重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //修改数据
        async lookDiary(row) {
            this.type = 2
            this.title = '修改用户信息'
            console.log(this.docsType);
            this.dialogFormVisible = true
            let result = await reqGetOne({ id: row._id })
            this.url = result.data.logo
            this.ruleForm = { ...result.data }
        },
        //照片墙
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        //获取用户数据
        async getAdminGroup() {
            let result = await reqAdminGroup()
            if (result.status == 200) {
                this.pageInfo = result.data.pageInfo
                this.docsType = result.data.docs
                console.log(result.data.docs
                );
            }
        },
        async getrAdminUser() {
            let result1 = await reqAdminUser()
            if (result1.status == 200) {
                // this.pageInfo = result.data.pageInfo
                this.docs = result1.data.docs
                console.log(this.docs);
            }
        },
        //分页
        async renderPageList(current = 1, pageSize = 10) {
            let searchkey = this.pageInfo ? this.pageInfo.searchkey : "";
            let state = this.pageInfo ? this.pageInfo.state : "";
            let user = this.pageInfo ? this.pageInfo.user : "";
            let targetCurrent = current;
            let result = await reqGetPage({
                current: targetCurrent,
                pageSize,
                searchkey
            });
            this.docs = result.data.docs
            //ComponentPaginationEnd
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            let current = this.pageInfo ? this.pageInfo.current : 1;
            this.renderPageList(current, val);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            let pageSize = this.pageInfo ? this.pageInfo.pageSize : 10;
            this.renderPageList(val, pageSize);
        }

    },
    mounted() {
        //挂载用户管理
        this.getAdminGroup()
        this.getrAdminUser()

    },
}
</script>

<style lang="scss">
.content-body {
    background-color: #f5f7f9;
    padding: 0 20px;

    .el-pagination {
        text-align: center;
        margin-top: 20px;
    }

    .content {
        .button-papa {
            margin-top: 25px;
            margin-left: 15px;

            .delete_danger {
                color: pink;
                background-color: #fef0f0;
            }

            .delete_danger:hover {
                background-color: #F56C6C;
            }

            .clear_danger {
                color: #E6A23C;
                background: #fdf6ec;
                border-color: #f5dab1;
            }

            .clear_danger:hover {
                color: #FFF;
                background-color: #E6A23C;
                border-color: #E6A23C;
            }
        }

        .content-center {
            .delete_danger {
                color: pink;
                background-color: #fef0f0;
            }

            .delete_danger:hover {
                background-color: #F56C6C;
            }

            .clear_danger {
                color: #409EFF;
                background: #ecf5ff;
                border-color: #b3d8ff;
            }

            .clear_danger:hover {
                color: #FFF;
                background-color: #409EFF;
                border-color: #409EFF;
            }
        }
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>